<template>

    <NuxtLayout name="manage-layout">
        <template #main>

            <div class="min-h-dvh flex justify-center">

                <div class="card bg-base-100 w-11/12 shadow-xl">
                    <div class="card-body">
                        <h4 class="card-title">用户列表</h4>
                        <div class="stats shadow w-56">
                            <div class="stat">
                                <div class="stat-figure flex gap-2">
                                    <div class="text-secondary cursor-pointer" @click="showFormModal(null)" v-if="'超级管理员' === loginUserRef.role || '教师' === loginUserRef.role">
                                        <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24"
                                             stroke-width="1.5"
                                             stroke="currentColor" class="size-6">
                                            <path stroke-linecap="round" stroke-linejoin="round"
                                                  d="M12 4.5v15m7.5-7.5h-15"/>
                                        </svg>
                                    </div>
                                    <div class="text-secondary cursor-pointer" @click="showBulkImportModal()" v-if="'超级管理员' === loginUserRef.role || '教师' === loginUserRef.role">
                                        <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24"
                                             stroke-width="1.5"
                                             stroke="currentColor" class="size-6">
                                            <path stroke-linecap="round" stroke-linejoin="round"
                                                  d="M3 16.5v2.25A2.25 2.25 0 0 0 5.25 21h13.5A2.25 2.25 0 0 0 21 18.75V16.5m-13.5-9L12 3m0 0 4.5 4.5M12 3v13.5"/>
                                        </svg>
                                    </div>
                                </div>
                                <div class="stat-title">数据量</div>
                                <div class="stat-value">{{ tableData.total }}</div>
                                <div class="stat-desc">共{{tableData.pages}}页数据</div>
                            </div>
                        </div>

                        <div class="flex flex-col gap-2">
                            <div class="flex flex-wrap gap-6">
                                <div class="form-control">
                                    <label class="label">
                                        <span class="label-text text-sm font-semibold">角色</span>
                                    </label>
                                    <select class="select select-bordered input-md min-w-32 w-full"
                                            v-model="searchForm.role">
                                        <option :value="undefined">全部</option>
                                        <option v-if="loginUserRef.role === '超级管理员'" :value="'超级管理员'">超级管理员</option>
                                        <option v-if="loginUserRef.role === '超级管理员'" :value="'教师'">教师</option>
                                        <option v-if="loginUserRef.role === '超级管理员' || loginUserRef.role === '教师'" :value="'学生'">学生</option>
                                    </select>
                                </div>
                                <div class="form-control">
                                    <label class="label">
                                        <span class="label-text text-sm font-semibold">账号</span>
                                    </label>
                                    <input type="text" v-model="searchForm.account"
                                           placeholder="请输入账号"
                                           class="input input-md input-bordered"/>
                                </div>
                                <div class="form-control">
                                    <label class="label">
                                        <span class="label-text text-sm font-semibold">姓名</span>
                                    </label>
                                    <input type="text" v-model="searchForm.name"
                                           placeholder="请输入姓名"
                                           class="input input-md input-bordered"/>
                                </div>
                                <div class="form-control">
                                    <label class="label">
                                        <span class="label-text text-sm font-semibold">手机号</span>
                                    </label>
                                    <phone-input v-model="searchForm.cellphoneNumber" />
                                </div>
                                <div class="form-control">
                                    <label class="label">
                                        <span class="label-text text-sm font-semibold">学校</span>
                                    </label>
                                    <input type="text" v-model="searchForm.xuexiao"
                                           placeholder="请输入学校"
                                           class="input input-md input-bordered"/>
                                </div>
                                <div class="form-control">
                                    <label class="label">
                                        <span class="label-text text-sm font-semibold">年级</span>
                                    </label>
                                    <input type="text" v-model="searchForm.nianji"
                                           placeholder="请输入年级"
                                           class="input input-md input-bordered"/>
                                </div>
                                <div class="form-control">
                                    <label class="label">
                                        <span class="label-text text-sm font-semibold">班级</span>
                                    </label>
                                    <input type="text" v-model="searchForm.banji"
                                           placeholder="请输入班级"
                                           class="input input-md input-bordered"/>
                                </div>
                                <div class="form-control">
                                    <label class="label">
                                        <span class="label-text text-sm font-semibold">学号/工号</span>
                                    </label>
                                    <input type="text" v-model="searchForm.xuehao"
                                           placeholder="请输入学号/工号"
                                           class="input input-md input-bordered"/>
                                </div>
                            </div>
                        </div>
                        <div class="flex">
                            <button class="btn btn-square btn-outline btn-md btn-info" @click="loadData()"
                                    title="查询">
                                <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24"
                                     stroke-width="1.5"
                                     stroke="currentColor" class="size-6">
                                    <path stroke-linecap="round" stroke-linejoin="round"
                                          d="m21 21-5.197-5.197m0 0A7.5 7.5 0 1 0 5.196 5.196a7.5 7.5 0 0 0 10.607 10.607Z"/>
                                </svg>
                            </button>
                        </div>


                        <div class="card bg-base-100 w-full shadow-xl">
                            <div class="card-body">
                                <div class="overflow-x-auto">
                                    <table class="table">
                                        <thead>
                                        <tr>
                                            <th>角色</th>
                                            <th>账号</th>
                                            <th>头像</th>
                                            <th>姓名</th>
                                            <th>手机号</th>
                                            <th>学校</th>
                                            <th>年级</th>
                                            <th>班级</th>
                                            <th>学号/工号</th>
                                            <th></th>
                                        </tr>
                                        </thead>
                                        <tbody>

                                        <tr v-for="item in tableData.list" class="hover">
                                            <td>{{item.role}}</td>
                                            <td>{{item.account}}</td>
                                            <td>
                                                <div class="avatar" v-if="item.headImgKey">
                                                    <div class="w-auto h-28 rounded rounded-xl">
                                                        <img :src="genFileUrl(item.headImgKey)"/>
                                                    </div>
                                                </div>
                                            </td>
                                            <td>{{item.name}}</td>
                                            <td>{{item.cellphoneNumber}}</td>
                                            <td>{{item.xuexiao}}</td>
                                            <td>{{item.nianji}}</td>
                                            <td>{{item.banji}}</td>
                                            <td>{{item.role === '学生' ? item.xuehao : (item.gonghao || item.xuehao)}}</td>
                                            <td>
                                                <button class="btn btn-xs mx-1 hover:bg-green-400" @click="showDetailsModal(item.id, item.role)" title="查看">
                                                    <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5"
                                                         stroke="currentColor" class="size-6 hover:text-white">
                                                        <path stroke-linecap="round" stroke-linejoin="round"
                                                              d="M2.036 12.322a1.012 1.012 0 0 1 0-.639C3.423 7.51 7.36 4.5 12 4.5c4.638 0 8.573 3.007 9.963 7.178.07.207.07.431 0 .639C20.577 16.49 16.64 19.5 12 19.5c-4.638 0-8.573-3.007-9.963-7.178Z"/>
                                                        <path stroke-linecap="round" stroke-linejoin="round"
                                                              d="M15 12a3 3 0 1 1-6 0 3 3 0 0 1 6 0Z"/>
                                                    </svg>
                                                </button>
                                                <button class="btn btn-xs mx-1 hover:bg-cyan-400" @click="showFormModal(item.id, item.role)"
                                                            :disabled="'学生' === loginUserRef.role"
                                                        title="编辑">
                                                    <svg xmlns="http://www.w3.org/2000/svg" fill="none"
                                                         viewBox="0 0 24 24" stroke-width="1.5"
                                                         stroke="currentColor" class="size-6 hover:text-white">
                                                        <path stroke-linecap="round" stroke-linejoin="round"
                                                              d="m16.862 4.487 1.687-1.688a1.875 1.875 0 1 1 2.652 2.652L10.582 16.07a4.5 4.5 0 0 1-1.897 1.13L6 18l.8-2.685a4.5 4.5 0 0 1 1.13-1.897l8.932-8.931Zm0 0L19.5 7.125M18 14v4.75A2.25 2.25 0 0 1 15.75 21H5.25A2.25 2.25 0 0 1 3 18.75V8.25A2.25 2.25 0 0 1 5.25 6H10"/>
                                                    </svg>
                                                </button>
                                                <button class="btn btn-xs mx-1 hover:bg-rose-400" @click="del(item.role, item.id)"
                                                            :disabled="'学生' === loginUserRef.role"
                                                        title="删除">
                                                    <svg xmlns="http://www.w3.org/2000/svg" fill="none"
                                                         viewBox="0 0 24 24" stroke-width="1.5"
                                                         stroke="currentColor" class="size-6 hover:text-white">
                                                        <path stroke-linecap="round" stroke-linejoin="round"
                                                              d="m14.74 9-.346 9m-4.788 0L9.26 9m9.968-3.21c.342.052.682.107 1.022.166m-1.022-.165L18.16 19.673a2.25 2.25 0 0 1-2.244 2.077H8.084a2.25 2.25 0 0 1-2.244-2.077L4.772 5.79m14.456 0a48.108 48.108 0 0 0-3.478-.397m-12 .562c.34-.059.68-.114 1.022-.165m0 0a48.11 48.11 0 0 1 3.478-.397m7.5 0v-.916c0-1.18-.91-2.164-2.09-2.201a51.964 51.964 0 0 0-3.32 0c-1.18.037-2.09 1.022-2.09 2.201v.916m7.5 0a48.667 48.667 0 0 0-7.5 0"/>
                                                    </svg>
                                                </button>
                                            </td>
                                        </tr>

                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>

                        <div class="card-actions justify-center mt-6">
                            <button @click="toPage(item)"
                                    :class="'join-item btn-xs btn' + (item === searchForm.page ? ' btn-neutral ' : '')"
                                    v-for="item in tableData.pagination">{{ item }}
                            </button>
                        </div>
                    </div>
                </div>


                <!--        详情弹出层-->
                <div>
                    <input type="checkbox" id="detailsModal" ref="detailsModalCheckboxRef" class="modal-toggle"
                           @change="detailsModalCheckboxChanged"/>
                    <div class="modal" role="dialog">
                        <div class="modal-box w-6/12 max-w-5xl modal-box-custom">
                            <div class="modal-action">
                                <label for="detailsModal"
                                       class="absolute right-4 top-4 cursor-pointer">
                                    <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="size-6">
                                        <path stroke-linecap="round" stroke-linejoin="round" d="M6 18 18 6M6 6l12 12" />
                                    </svg>
                                </label>
                            </div>
                            <h3 class="text-lg font-bold">查看详情</h3>
                            <div class="mt-4" v-if="detailsData !== null">
                                <div class="form-control">
                                    <label class="label">
                                        <span class="label-text font-semibold">角色</span>
                                    </label>
                                    <span class="text-sm">{{detailsData.role}}</span>
                                </div>
                                <div class="form-control">
                                    <label class="label">
                                        <span class="label-text font-semibold">账号</span>
                                    </label>
                                    <span class="text-sm">{{detailsData.account}}</span>
                                </div>
                                <div class="form-control">
                                </div>
                                <div class="form-control">
                                    <label class="label">
                                        <span class="label-text font-semibold">姓名</span>
                                    </label>
                                    <span class="text-sm">{{detailsData.name}}</span>
                                </div>
                                <div class="form-control">
                                    <label class="label">
                                        <span class="label-text font-semibold">手机号</span>
                                    </label>
                                    <span class="text-sm">{{detailsData.cellphoneNumber}}</span>
                                </div>
                                <div class="form-control">
                                    <label class="label">
                                        <span class="label-text font-semibold">学校</span>
                                    </label>
                                    <span class="text-sm">{{detailsData.xuexiao}}</span>
                                </div>
                                <div class="form-control">
                                    <label class="label">
                                        <span class="label-text font-semibold">年级</span>
                                    </label>
                                    <span class="text-sm">{{detailsData.nianji}}</span>
                                </div>
                                <div class="form-control">
                                    <label class="label">
                                        <span class="label-text font-semibold">班级</span>
                                    </label>
                                    <span class="text-sm">{{detailsData.banji}}</span>
                                </div>
                                <div class="form-control">
                                    <label class="label">
                                        <span class="label-text font-semibold">{{ detailsData.role === '学生' ? '学号' : '工号' }}</span>
                                    </label>
                                    <span class="text-sm">{{detailsData.role === '学生' ? detailsData.xuehao : (detailsData.gonghao || detailsData.xuehao)}}</span>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!--        编辑弹出层-->
                <dialog-modal ref="formDialogModalRef">
                    <template #main>
                        <div class="form-control">
                            <label class="label">
                                <span class="label-text text-sm font-semibold">角色</span>
                            </label>
                            <select class="select select-bordered input-md w-full max-w-xs" v-model="form.role">
                                <option :value="undefined">未选择</option>
                                <option v-if="loginUserRef.role === '超级管理员'" :value="'超级管理员'">超级管理员</option>
                                <option v-if="loginUserRef.role === '超级管理员'" :value="'教师'">教师</option>
                                <option v-if="loginUserRef.role === '超级管理员' || loginUserRef.role === '教师'" :value="'学生'">学生</option>
                            </select>
                        </div>
                        <div class="form-control">
                            <label class="label">
                                <span class="label-text text-sm font-semibold">账号</span>
                            </label>
                            <input type="text" v-model="form.account" placeholder="请输入账号"
                                   class="input input-md input-bordered"/>
                        </div>
                        <div class="form-control">
                            <label class="label">
                                <span class="label-text text-sm font-semibold">密码</span>
                            </label>
                            <input type="password" v-model="form.password" placeholder="请输入密码"
                                   class="input input-md input-bordered"/>
                        </div>
                        <div class="form-control">
                            <label class="label">
                                <span class="label-text text-sm font-semibold">姓名</span>
                            </label>
                            <input type="text" v-model="form.name" placeholder="请输入姓名"
                                   class="input input-md input-bordered"/>
                        </div>
                        <div class="form-control">
                            <label class="label">
                                <span class="label-text text-sm font-semibold">手机号</span>
                            </label>
                            <phone-input v-model="form.cellphoneNumber" />
                        </div>
                        <div class="form-control" v-if="form.role === '教师' || form.role === '学生'">
                            <label class="label">
                                <span class="label-text text-sm font-semibold">学校</span>
                            </label>
                            <input type="text" 
                                   v-model="form.xuexiao" 
                                   placeholder="请输入学校"
                                   class="input input-md input-bordered"
                                   :disabled="loginUserRef.role === '教师'"/>
                        </div>
                        <div v-if="form.role === '学生'" class="flex flex-col gap-2">
                            <div class="form-control">
                                <label class="label">
                                    <span class="label-text text-sm font-semibold">年级</span>
                                </label>
                                <select class="select select-bordered input-md w-full" v-model="form.nianji">
                                    <option :value="undefined">未选择</option>
                                    <option value="一年级">一年级</option>
                                    <option value="二年级">二年级</option>
                                    <option value="三年级">三年级</option>
                                    <option value="四年级">四年级</option>
                                    <option value="五年级">五年级</option>
                                    <option value="六年级">六年级</option>
                                </select>
                            </div>
                            <div class="form-control">
                                <label class="label">
                                    <span class="label-text text-sm font-semibold">班级</span>
                                </label>
                                <number-count :min="1" :max="99" v-model="form.banji" />
                            </div>
                        </div>
                        <div class="form-control">
                            <label class="label">
                                <span class="label-text text-sm font-semibold">{{ idFieldLabel }}</span>
                            </label>
                            <number-count :min="1" :max="9999999" v-model="form.xuehao" />
                        </div>
                    </template>
                    <template #footer>
                        <div>
                            <button class="btn bg-green-400 hover:bg-green-500 text-white" @click="submitForm()">提交</button>
                        </div>
                    </template>
                </dialog-modal>

                <!-- Bulk Import Modal -->
                <dialog-modal ref="bulkImportDialogModalRef">
                    <template #main>
                        <bulk-user-import @import-complete="handleImportComplete" @import-cancel="handleImportCancel" />
                    </template>
                </dialog-modal>

            </div>
        </template>
    </NuxtLayout>


</template>

<script setup>

import {httpDel, httpGet, httpPost, genFileUrl, postForm} from "~/utils/http/http-helper.js";
import {generatePaginationArray} from "~/utils/pagination/index.js";
import {notificationError, notificationSuccess, notificationWarning} from "~/utils/notification/index.js";
import auth from "~/utils/auth/index.js";
import BulkUserImport from '~/components/bulkUserImport.vue'

definePageMeta({
    index: 'manage-user',
})

const formDialogModalRef = ref()
const detailsModalCheckboxRef = ref()
const bulkImportDialogModalRef = ref()

const searchForm = ref({
    page: 1,
    size: 10,
})
const tableData = ref({
    list: [],
    total: 0,
    pages: '',
    pagination: []
})

const form = ref({})
const detailsData = ref(null)
const loginUserRef = ref({})

watch(() => form.value, (newVal) => {
    console.log('Form value changed:', newVal)
}, { deep: true })

/**
 * 加载登录用户
 */
function loadLoginUser(){
    const localUser = auth.getLocalUser()
    if(null !== localUser){
        loginUserRef.value = localUser
    }
}

/**
 * 初始化表单
 */
function initForm() {
    form.value = {}
    detailsData.value = null
}

function detailsModalCheckboxChanged(event) {
    const checked = event.target.checked
    if (checked) {
    } else {
    }
}

/**
 * 展示详情弹出层
 * @param id  主键ID
 * @param role 用户角色
 */
function showDetailsModal(id, role) {
    console.log('Opening details modal for user:', { id, role }) // Debug log
    httpGet(`/api/user/${role}/${id}`).then(resp => {
        if (!resp.success) {
            notificationError(resp.msg)
            return
        }
        const data = resp.data
        detailsData.value = data
        detailsModalCheckboxRef.value.checked = true
    })
}

/**
 * 关闭详情弹出层
 */
function closeDetailsModal() {
    detailsModalCheckboxRef.value.checked = false
    initForm()
}

/**
 * 关闭表单弹出框
 */
function closeFormModal() {
    formDialogModalRef.value.closeDialogModal()
    initForm()
}

/**
 * 表单提交
 * 新增或者更新
 */
function submitForm() {
    if (detailsData.value === null) {
        // 新增
        const submitData = {
            ...form.value,
            xuehao: form.value.xuehao // Ensure xuehao is included
        }
        console.log('Submitting new user data:', submitData) // Debug log
        httpPost('/api/user', submitData).then(resp => {
            if (resp.success) {
                notificationSuccess('添加用户成功')
                closeFormModal()
                loadData()
            } else {
                notificationError(resp.msg)
            }
        })
    } else {
        // 更新
        const submitData = {
            ...form.value,
            xuehao: form.value.xuehao // Ensure xuehao is included
        }
        console.log('Submitting update data:', submitData) // Debug log
        httpPost('/api/user/' + detailsData.value.id, submitData).then(resp => {
            if (resp.success) {
                notificationSuccess('编辑用户成功')
                closeFormModal()
                loadData()
            } else {
                notificationError(resp.msg)
            }
        })
    }
}

if (process.client) {
    loadLoginUser()
    loadData()
}

/**
 * 加载分页数据
 */
function loadData() {
    httpGet('/api/user', searchForm.value).then(resp => {
        console.log('API Response for user list:', resp) // Debug log
        if (!resp.success) {
            notificationError(resp.msg)
            return
        }
        const data = resp.data
        // 数据总数
        const total = data.totalElements
        tableData.value.list = data.content
        console.log('Table data loaded with users:', data.content.map(u => ({ id: u.id, account: u.account, name: u.name }))) // Debug log
        tableData.value.total = total
        tableData.value.pages = data.pages
        // 当前页码
        const currentPage = searchForm.value.page
        const pageSize = searchForm.value.size
        const pagination = generatePaginationArray(total, pageSize, currentPage); // 生成分页数组
        tableData.value.pagination = pagination
    })
}

/**
 * 跳转到某页
 * @param selectedPage  页码
 */
function toPage(selectedPage) {
    searchForm.value.page = selectedPage
    loadData()
}

/**
 * 展示模态框
 * @param id  主键ID null则为新增
 * @param role 用户角色
 */
function showFormModal(id, role) {
    console.log('Opening edit modal for user:', { id, role }) // Debug log
    initForm()
    if (null !== id) {
        httpGet(`/api/user/${role}/${id}`).then(resp => {
            if (!resp.success) {
                notificationError(resp.msg)
                return
            }
            const data = resp.data
            console.log('API Response Data for ID', id, ':', data) // Debug log
            detailsData.value = data
            // Handle the ID field based on role
            if (data.role === '学生') {
                console.log('Form value before assignment:', form.value)
                console.log('Student data before assignment:', data) // Debug log
                
                // First set the base data
                form.value = { ...data, xuehao: Number(data.xuehao)};
                
                console.log('Form value after assignment:', toRaw(form.value)) // Debug log
                console.log('Form xuehao after assignment:', form.value.xuehao) // Debug log
            } else {
                form.value = {
                    ...data,
                    xuehao: data.gonghao
                }
                console.log('Form value after assignment:', form.value) 
            }
            
            // Force a reactive update
            nextTick(() => {
                console.log('Final form value:', form.value)
                formDialogModalRef.value.showDialogModal('修改用户')
            })
        })
    } else {
        formDialogModalRef.value.showDialogModal('添加用户')
    }
}

/**
 * 删除
 * @param role 用户角色
 * @param id  主键ID
 */
function del(role, id) {
    httpDel(`/api/user/${role}/${id}`).then(resp => {
        if (resp.success) {
            notificationSuccess('删除用户成功')
            loadData()
        } else {
            notificationError(resp.msg)
        }
    })
}

watch(() => form.value.role, (newRole) => {
    if (loginUserRef.value.role === '教师') {
        form.value.xuexiao = loginUserRef.value.xuexiao
    }
}, { immediate: true })

// Add a computed property for the ID field label
const idFieldLabel = computed(() => {
    return form.value.role === '学生' ? '学号' : '工号'
})

function showBulkImportModal() {
    bulkImportDialogModalRef.value.showDialogModal('批量导入用户')
}

function handleImportComplete() {
    bulkImportDialogModalRef.value.closeDialogModal()
    loadData()
}

function handleImportCancel() {
    bulkImportDialogModalRef.value.closeDialogModal()
}
</script>

<style scoped>

</style>